import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import { ArticleStatus } from 'api/constants'
import { getArticles, delArticles } from 'api/articles'
import defultImg from 'assets/error.png'
import Channel from 'pages/Channel'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'

export default class ArticleList extends Component {
  state = {
    articles: [],
    total: 0,
    page: 0,
    pageSize: 0,
  }
  reqparams = {
    page: 1,
    per_page: 10,
  }
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(data) {
        const { images, type } = data
        // 当 type 为 0 是说明没有图
        if (type === 0) {
          return (
            <img
              src={defultImg}
              alt=""
              style={{ width: 200, height: 150, objectFit: 'cover' }}
            />
          )
        } else {
          return (
            <img
              src={images[0]}
              alt=""
              style={{ width: 200, height: 150, objectFit: 'cover' }}
            />
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(data) {
        const obj = ArticleStatus.find((item) => {
          return data === item.id && item
        })
        // console.log(obj)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                this.handelEdit(data.id)
              }}
            />
            <Button
              danger
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => this.handelClick(data.id)}
            />
          </Space>
        )
      },
    },
  ]
  render() {
    const { articles, total, page, pageSize } = this.state
    return (
      <div>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          {/* initialValues是刷新页面之后一开始选定的值 */}
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleStatus.map((obj) => {
                  return (
                    <Radio value={obj.id} key={obj.id}>
                      {' '}
                      {obj.name}
                    </Radio>
                  )
                })}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              {/* 中文包在全局被导入 */}
              <DatePicker.RangePicker />
            </Form.Item>
            <Form.Item>
              <Button htmlType="submit" type="primary">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件共查询到 ${total}条结果:`}>
          <Table
            columns={this.columns}
            dataSource={articles}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              current: page,
              total,
              pageSize,
              onChange: this.changeFn,
            }}
          />
        </Card>
      </div>
    )
  }
  handelEdit(id) {
    // console.log(id)
    this.props.history.push(`/home/publish/${id}`)
  }
  handelClick(id) {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章?',
      onOk: async () => {
        await delArticles(id)
        this.getArticleList()
        message.success('删除成功')
      },
    })
  }
  changeFn = (page, pageSize) => {
    this.reqparams.page = page
    this.reqparams.per_page = pageSize
    this.getArticleList()
  }
  onFinish = ({ status, channel_id, date }) => {
    status !== -1
      ? (this.reqparams.status = status)
      : delete this.reqparams.status
    channel_id !== undefined
      ? (this.reqparams.channel_id = channel_id)
      : delete this.reqparams.channel_id
    if (date) {
      this.reqparams.begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      this.reqparams.end_pubdate = date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete this.reqparams.begin_pubdate
      delete this.reqparams.end_pubdate
    }
    // console.log(this.reqparams)
    // console.log(channel_id)
    // console.log(date);
    this.getArticleList()
  }
  async componentDidMount() {
    this.getArticleList()
  }
  async getArticleList() {
    const { data } = await getArticles(this.reqparams)
    // console.log(data)
    this.setState({
      articles: data.results,
      total: data.total_count,
      pageSize: data.per_page,
      page: data.page,
    })
  }
}
